package global

import (
	"crypto/sha512"
	"fmt"
	"github.com/anaskhan96/go-password-encoder"
	"gorm.io/gorm"
	"pm_back_server/user-server/config"
	"strings"
)

var (
	DB           *gorm.DB
	ServerConfig *config.ServerConfig
)

const (
	SaltLen    = 16
	Iterations = 100
	KeyLen     = 32
)

// 加密配置项
var options = &password.Options{SaltLen: SaltLen, Iterations: Iterations, KeyLen: KeyLen, HashFunction: sha512.New}

// Encode /* 将密码进行md5加密
func Encode(rawPassword string) string {
	salt, encodedPwd := password.Encode(rawPassword, options)
	newPassword := fmt.Sprintf("$userpwd-sha512$%s$%s", salt, encodedPwd)
	return newPassword
}

// Verify /* 验证密码
func Verify(rawPassword string, encodePassword string) bool {
	list := strings.Split(encodePassword, "$")
	check := password.Verify(rawPassword, list[2], list[3], options)
	return check
}
